<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/23
 * Time: 11:12
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\Customer;
use zhtfrontend\models\datas\Complaint;
use zhtfrontend\models\datas\Mechanic;
use yii\bootstrap\ActiveForm;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;


class ComplaintController extends \zhtfrontend\components\bases\BaseController
{
    public $service_arr = [1=>'接待不热情',2=>'介绍课程不清晰',3=>'没有学员课后学习的反馈'];
    public $teaching_arr = [1=>'课程内容不成体系',2=>'教师只关注部分孩子',3=>'教师授课水平需要提升'];
    public $environmental_arr = [1=>'教室不干净整洁',2=>'卫生间卫生条件差',3=>'没有家长休息区'];

    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            $data = Complaint::find()->orderBy('id DESC');
            if (!empty($param['searchData'])) {
                $search_data = $param['searchData'];
                if (!empty($search_data['name'])) {
                    $cids = Customer::find()->select('id')->where(['like','name',$search_data['name']])->column();
                    $data->andWhere(['customer_id'=>$cids]);
                }
                if (!empty($search_data['mechanic_name'])) {
                    $mids = Mechanic::find()->select('id')->where(['like','name',$search_data['mechanic_name']])->column();
                    $data->andWhere(['mechanic_id'=>$mids]);
                }
                if(isset($search_data['status']) && $search_data['status'] != null){
                    $data->andWhere(['status'=>$search_data['status']]);
                }
                if(!empty($search_data['is_satisfied'])){
                    $data->andWhere(['is_satisfied'=>$search_data['is_satisfied']]);
                }
            }
            if(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'business_director') {
                $mids = Mechanic::find()->where(['admin_id'=>\Yii::$app->user->id])->column();
                $data->andWhere(['id'=>$mids]);
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $list = Fun::asArray($model, ['customer_name','operate','mechanic_name','mobile']);
            foreach($list as $k=>$val){
                $list[$k]['service_level'] = !empty($this->service_arr[$val['service_level']])?$this->service_arr[$val['service_level']]:'';
                $list[$k]['teaching_level'] = !empty($this->teaching_arr[$val['teaching_level']])?$this->teaching_arr[$val['teaching_level']]:'';
                $list[$k]['environmental_level'] = !empty($this->environmental_arr[$val['environmental_level']])?$this->environmental_arr[$val['environmental_level']]:'';
            }
//            $ajax_object = new AjaxObject();
//            $ajax_object->data =$list;
//            $ajax_object->pages = $pages;
//            return $ajax_object;


        return $this->render('index',['data'=>$list,'pages'=>$pages]);
    }

    public function actionHandle(){
        $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Complaint::findOne($id);
        if($model == null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'handle';
        if($model->status == 0){
            $model->status = 1;
        }

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $model->admin_id = \Yii::$app->user->id;
            $model->admin_name = \Yii::$app->user->identity->name;
            $model->updated_at = time();
            $model->is_satisfied = 0;
            $new_remarks = $model->new_remark."\n". \Yii::$app->formatter->asDatetime(time());
            $str = '';
            if(!empty($model->remarks)){
                $str = $model->remarks."\n";
            }
            $model->remarks = $str.$new_remarks;
            $title = '投诉处理';
            $m_name = isset($model->mechanic)?$model->mechanic->name:'';
            if($model->save(false)){
                $m = '';
                $delay = 1;
                if($model->status > 0){
                    $str = "投诉机构：" . $m_name . "\n处理状态：";
                    if ($model->status == 1) {
                        $str .= "处理中 \n";
                    } elseif ($model->status == 2) {
                        $str .= "处理完成！\n";
                    } elseif ($model->status == 3) {
                        $str .= "投诉驳回 \n";
                    }
                    if (!empty($model->remarks)) {
                        $str .= "描述：".$model->remarks;
                    }
                    $res = (new ManualWechatMessage([
                        'customer_id' => $model->customer_id,
                        'title'=>$title,
                        'desc' => $str,
                        'url'  => '/complaint/list?site_id='.Fun::getSiteId(),
                        'site_id' => Fun::getSiteId()
                    ]))->send();
                    if($res > 0){
                        $m = '--微信消息发送失败请电话联系';
                        $delay = 5;
                    }
                }
                return $this->redirectMessage('处理成功'.$m, Fun::url(['complaint/index'],false,[],'','success',$delay));
            }else{
                return $this->redirectMessage('处理失败', Fun::url(['complaint/index']));
            }
        }

        return $this->render('handle',['model'=>$model,'service'=>$this->service_arr,'teaching'=>$this->teaching_arr,'environmental'=>$this->environmental_arr]);
    }

    public function actionView(){
        $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Complaint::findOne($id);
        if($model == null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        return $this->render('view',['model'=>$model,'service'=>$this->service_arr,'teaching'=>$this->teaching_arr,'environmental'=>$this->environmental_arr]);
    }




}